package com.zeros.baselibrary.ext

import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import com.trello.rxlifecycle.LifecycleProvider
import com.zeros.baselibrary.data.protocol.BaseResp
import com.zeros.baselibrary.rx.BaseFunc
import com.zeros.baselibrary.rx.BaseFuncBoolean
import com.zeros.baselibrary.rx.BaseSubscriber
import com.zeros.baselibrary.utils.GlideUtils
import com.zeros.baselibrary.widgets.DefaultTextWatcher
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

/**
 * Kotlin通用扩展   ▏2018/5/16.
 */

//--------------------RxKotlin中的方法-----------------
/*-1.扩展Observable执行-*/
fun <T> Observable<T>.excute(subscriber: BaseSubscriber<T>, lifecycleProvider: LifecycleProvider<*>) {
    this.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .compose(lifecycleProvider.bindToLifecycle())
            .subscribe(subscriber)
}

/*-2.扩展通用数据转换-*/
fun <T> Observable<BaseResp<T>>.convert(): Observable<T> {
    return this.flatMap(BaseFunc())
}

/*-3.扩展Boolean类型数据转换(只有布尔型需要单独提取出来)-*/
fun <T> Observable<BaseResp<T>>.convertBoolean(): Observable<Boolean> {
    return this.flatMap(BaseFuncBoolean())
}


//-----------------View中的方法----------------------
/*-4.扩展点击事件-*/
fun View.onClick(listener: View.OnClickListener): View {
    setOnClickListener(listener)
    return this
}

/*-5.扩展点击事件，参数为方法-*/
fun View.onClick(method: () -> Unit): View {
    setOnClickListener { method() }
    return this
}

//-----------------Button扩展-----------------------

/*-6.扩展Button可用性-*/
fun Button.enable(et: EditText, method: () -> Boolean) {
    val bth = this
    et.addTextChangedListener(object : DefaultTextWatcher() {
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            bth.isEnabled = method()
        }
    })
}

//-------------ImageView扩展--------------------
/*-7.ImageView加载网络图片-*/
fun ImageView.loadUrl(url: String) {
    GlideUtils.loadUrlImage(context, url, this)
}

